<template>
	<div class="bg">
		<goback title="我的排名"></goback>


		<ul class="TopNav">
			<li @click="changeSwiper(0)" :class="{ 'select': activePage === 0 }">
				积分排名
			</li>
			<li @click="changeSwiper(1)" :class="{ 'select': activePage === 1 }">
				环保排名
			</li>
			<li @click="changeSwiper(2)" :class="{ 'select': activePage === 2 }">
				答题排名
			</li>
		</ul>

		<swiper class="swiper-container" @slideChange="onSlideChange" ref="mySwiper">
			<swiper-slide class="swiper-slide">
				<div class="card">
					<div class="card_title">积分排名</div>
					<div class="card_row_line" v-for="(item,index) in getSevenScore" :key="index">
						<img class="card_row_line_img" :src="item.head_img" alt="" />
						<div class="card_row_line_user">
							<div>No.{{index+1}}</div>
							<div class="card_row_line_user_name">{{item.name}}</div>
						</div>
						<div class="card_row_line_score">{{item.score}}分</div>
					</div>




					<div class="chart-container">
						<div id="my_bar_chart1" class="chart"></div>
					</div>

					<div class="sum">
						<div>您当前最新排名是第<span>{{getScoreRank}}</span>名</div>
						<div>距超越上一名还差<span>{{getLastScoreDistance}}</span>分</div>
						<div>累计超越全站<span>{{((users.length-getScoreRank+1)/users.length*100).toFixed(2)}}%</span>的用户</div>
					</div>

				</div>
			</swiper-slide>
			<swiper-slide class="swiper-slide">
				<div class="card">



					<div class="card">
						<div class="card_title">企业排名</div>
						<div class="card_row_line" v-for="(item, index) in giveThreeBusiness" :key="item.id">
							<img class="card_row_line_img" :src="item.head_img" alt="" />
							<div class="card_row_line_user">
								<div>No.{{ index + 1 }}</div>
								<div class="card_row_line_user_name">{{ item.name }}</div>
							</div>
							<div class="card_row_line_score">{{ item.buy + item.sell }} Co²</div>
						</div>
					</div>
					<div class="card">
						<div class="card_title">农户排名</div>
						<div class="card_row_line" v-for="(item, index2) in giveThreeFarmer" :key="item.id">
							<img class="card_row_line_img" :src="item.head_img" alt="" />
							<div class="card_row_line_user">
								<div>No.{{ index2 + 1 }}</div>
								<div class="card_row_line_user_name">{{ item.name }}</div>
							</div>
							<div class="card_row_line_score">{{ item.buy + item.sell }} Co²</div>
						</div>
					</div>


					<div class="chart-container">
						<div id="my_bar_chart2" class="chart"></div>
					</div>

					<div class="sum">
						<div>您当前最新排名是第<span>{{getCollectRank}}</span>名</div>
						<div>距离超越上一名还差减少释放<span>{{getLastCollectDistance}}L</span>Co²气体</div>
						<div>累计超越全站<span>{{((users.length-getCollectRank+1)/users.length*100).toFixed(2)}}%</span>的用户</div>
					</div>

				</div>
			</swiper-slide>
			<swiper-slide class="swiper-slide">
				<div class="card">
					<div class="card_title">正确率</div>
					<div class="card_row_line" v-for="(item,index) in getTenCorrect" :key="index">
						<img class="card_row_line_img" :src="item.head_img" alt="" />
						<div class="card_row_line_user">
							<div>No.{{index+1}}</div>
							<div class="card_row_line_user_name">{{item.name}}</div>
						</div>
						<div class="card_row_line_score">{{item.correctpercentage}}%</div>
					</div>



					<div class="chart-container">
						<div id="my_bar_chart3" class="chart"></div>
					</div>

					<div class="sum">
						<div>您当前最新排名是第<span>{{getCorrectRank}}</span>名</div>
						<div>距离超越上一名还差<span>{{getLastCorrectDistance}}%</span>概率</div>
						<div>累计超越全站<span>{{((users.length-getCorrectRank+1)/users.length*100).toFixed(2)}}%</span>的用户</div>
					</div>

				</div>
			</swiper-slide>
		</swiper>

	</div>
</template>

<script>
	import * as echarts from "echarts";
	export default {
		name: "rank",
		data() {
			return {
				activePage: 0,
				userID: this.$store.getters.getUser.uid,
				users: [],
				/* {
						name: '用户H',
						head_img: '头像.jpg',
						score: 0,
						achievements: 18,
						sell: 0,
						buy: 333,
						friendship_num: 13,
						question_yes: 125,
						question_no: 12,
						correctpercentage: 0
					}
					*/
			};
		},
		mounted() {
			this.initData();
		},
		computed: {
			getSevenScore() {
				// 浅拷贝原数组  
				const sortedUsers = [...this.users].sort((b, a) => {
					if (a.score > b.score) {
						return 1;
					} else if (a.score < b.score) {
						return -1;
					} else {
						return 0;
					}
				});
				// 返回前五个排序后的用户  
				return sortedUsers.slice(0, 7);
			},
			giveThreeBusiness() {

				const filterArr = this.users.filter((a) => {
					return a.position==1;
				})


				const sortedUsers = filterArr.sort((b, a) => {
					if (a.sell + a.buy > b.sell + b.buy) {
						return 1;
					} else if (a.sell + a.buy < b.sell + b.buy) {
						return -1;
					} else {
						return 0;
					}
				});
				// 返回前五个排序后的用户  
				return sortedUsers.slice(0, 3);
			},

			giveThreeFarmer() {

				const filterArr = this.users.filter((a) => {
					return a.position==0;
				})


				const sortedUsers = filterArr.sort((b, a) => {
					if (a.sell + a.buy > b.sell + b.buy) {
						return 1;
					} else if (a.sell + a.buy < b.sell + b.buy) {
						return -1;
					} else {
						return 0;
					}
				});
				// 返回前五个排序后的用户  
				return sortedUsers.slice(0, 3);
			},
			getTenCorrect() {

				this.users.forEach(e => {
					e.correctpercentage = +(e.question_yes / (e.question_yes + e.question_no) * 100).toFixed(1);
				})


				const sortedUsers = [...this.users].sort((b, a) => {
					if (a.question_yes / (a.question_yes + a.question_no) > b.question_yes / (b.question_yes + b
							.question_no)) {
						return 1;
					} else if (a.question_yes / (a.question_yes + a.question_no) < b.question_yes / (b
							.question_yes + b.question_no)) {
						return -1;
					} else {
						return 0;
					}
				});
				// 返回前五个排序后的用户  
				return sortedUsers.slice(0, 10);
			},
			getScoreRank() {
				const tempArr = [...this.users].sort((b, a) => {
					if (a.score > b.score) {
						return 1;
					} else if (a.score < b.score) {
						return -1;
					} else {
						return 0;
					}
				});
				for (let i = 0; i < tempArr.length; i++) {
					if (tempArr[i].uid == this.userID) {
						return i + 1;
						break;
					}
				};
			},
			getCollectRank() {
				const tempArr = [...this.users].sort((b, a) => {
					if (a.sell + a.buy > b.sell + b.buy) {
						return 1;
					} else if (a.sell + a.buy < b.sell + b.buy) {
						return -1;
					} else {
						return 0;
					}
				});
				for (let i = 0; i < tempArr.length; i++) {
					if (tempArr[i].uid == this.userID) {
						return i + 1;
						break;
					}
				};
			},
			getCorrectRank() {
				const tempArr = [...this.users].sort((b, a) => {
					if (a.question_yes / (a.question_yes + a.question_no) > b.question_yes / (b.question_yes + b
							.question_no)) {
						return 1;
					} else if (a.question_yes / (a.question_yes + a.question_no) < b.question_yes / (b
							.question_yes + b.question_no)) {
						return -1;
					} else {
						return 0;
					}
				});
				for (let i = 0; i < tempArr.length; i++) {
					if (tempArr[i].uid == this.userID) {
						return i + 1;
						break;
					}
				};
			},


			getLastScoreDistance() {
				const tempArr = [...this.users].sort((b, a) => {
					if (a.score > b.score) {
						return 1;
					} else if (a.score < b.score) {
						return -1;
					} else {
						return 0;
					}
				});

				let now_index = 0;
				for (let i = 0; i < tempArr.length; i++) {
					if (tempArr[i].uid == this.userID) {
						now_index = i;
						break;
					}
				};

				if (now_index == 0) {
					return 0;
				} else {
					return tempArr[now_index - 1].score - tempArr[now_index].score;
				}
			},

			getLastCollectDistance() {
				const tempArr = [...this.users].sort((b, a) => {
					if (a.sell + a.buy > b.sell + b.buy) {
						return 1;
					} else if (a.sell + a.buy < b.sell + b.buy) {
						return -1;
					} else {
						return 0;
					}
				});

				let now_index = 0;
				for (let i = 0; i < tempArr.length; i++) {
					if (tempArr[i].uid == this.userID) {
						now_index = i;
						break;
					}
				};

				if (now_index == 0) {
					return 0;
				} else {
					return tempArr[now_index - 1].score - tempArr[now_index].score;
				}
			},

			getLastCorrectDistance() {
				const tempArr = [...this.users].sort((b, a) => {
					if (a.question_yes / (a.question_yes + a.question_no) > b.question_yes / (b.question_yes + b
							.question_no)) {
						return 1;
					} else if (a.question_yes / (a.question_yes + a.question_no) < b.question_yes / (b
							.question_yes + b.question_no)) {
						return -1;
					} else {
						return 0;
					}
				});

				let now_index = 0;
				for (let i = 0; i < tempArr.length; i++) {
					if (tempArr[i].uid == this.userID) {
						now_index = i;
						break;
					}
				};

				if (now_index == 0) {
					return 0;
				} else {
					return (tempArr[now_index - 1].correctpercentage - tempArr[now_index].correctpercentage).toFixed(1);
				}
			},


		},
		methods: {
			getSrc() {
				this.users.forEach((e) => {
					let url = `${this.IP}/img/${e.uid}.jpg`
					e.head_img = url
				})
			},
			
			initData(){
				this.axios.get(`${this.IP}/get_rank`, {
					params: {
				
					}
				}).then(res => {
					console.log(res.data);
					this.users=res.data; 
					this.getSrc();
					this.updateScoreBar();
					this.updateCollectLine();
					this.updateCorrect();
				}).catch(error => {
					// 处理错误  
					console.error('请求出错：', error);
				});;
				
			},
			onSlideChange() {
				this.activePage = this.$refs.mySwiper.swiperInstance.activeIndex;
				console.log(this.activePage);
			},
			changeSwiper(e) {
				this.$refs.mySwiper.swiperInstance.activeIndex = e;
				this.activePage = e;
			},

			updateScoreBar() {
				var scoreGroups = {
					'0': 0,
					'1-10': 0,
					'11-30': 0,
					'31-50': 0,
					'51-1000': 0
				};

				// 遍历用户数据，计算每个区间的人数  
				this.users.forEach((user) => {
					if (user.score <= 0) {
						scoreGroups['0']++;
					} else if (user.score <= 10) {
						scoreGroups['1-10']++;
					} else if (user.score <= 30) {
						scoreGroups['11-30']++;
					} else if (user.score <= 50) {
						scoreGroups['31-50']++;
					} else {
						scoreGroups['51-1000']++;
					}
				});

				// 计算总人数  
				var totalUsers = this.users.length;
				var totalPercentage = 100; // 总百分比为100%  

				// 转换分组数据为适合ECharts的格式  
				var xDataArr = []; // 横坐标数据（人数百分比）  
				var yDataArr = Object.keys(scoreGroups); // 纵坐标数据（分数区间）  
				var seriesData = []; // 系列数据，用于显示条形图的长度  

				for (var group in scoreGroups) {
					var count = scoreGroups[group];
					var percentage = (count / totalUsers * totalPercentage).toFixed(2); // 计算百分比  
					xDataArr.push(percentage + '%'); // 人数百分比作为横坐标数据  
					seriesData.push(percentage); // 百分比值作为系列数据  
				}

				// 设置ECharts的配置项和数据  
				var barChart = echarts.init(document.getElementById("my_bar_chart1"));
				barChart.setOption({
					title: {
						text: '不同积分段的人数比例横向柱形图',
						left: 'center', // 标题居中显示  
						textStyle: { // 标题样式，可根据需要调整  
							color: '#000', // 标题颜色  
							fontSize: 18, // 标题字体大小 
							fontWeight: 'normal'
						}
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'shadow'
						}
					},
					xAxis: {
						type: 'value',
						axisLabel: {
							formatter: '{value}%' // 显示百分比格式  
						},
						min: 0,
						max: totalPercentage // 设置x轴的最大值为100%  
					},
					yAxis: {
						type: 'category',
						data: yDataArr,
						name: '积分',
						axisLabel: {
							interval: 0, // 强制显示所有标签  ，
						},
					},
					series: [{
						data: seriesData,
						name: '人数占比（%）',
						type: 'bar',
						barWidth: '50%', // 设置条形图的宽度  
						label: {
							show: true,
							position: 'right' // 标签位置  
						},
						itemStyle: {
							color: '#5793f3' // 条形图颜色  
						}
					}]
				});
			},




			updateCollectLine() {
				var scoreGroups = {
					'0-50': 0,
					'51-100': 0,
					'101-300': 0,
					'301-500': 0,
					'501-1000': 0
				};

				// 遍历用户数据，计算每个区间的人数  
				this.users.forEach((user) => {
					if (user.buy + user.sell <= 50) {
						scoreGroups['0-50']++;
					} else if (user.buy + user.sell <= 100) {
						scoreGroups['51-100']++;
					} else if (user.buy + user.sell <= 300) {
						scoreGroups['101-300']++;
					} else if (user.buy + user.sell <= 500) {
						scoreGroups['301-500']++;
					} else {
						scoreGroups['501-1000']++;
					}
				});

				var barChart = echarts.init(document.getElementById("my_bar_chart2"));
				var xDataArr = Object.keys(scoreGroups); // 横坐标：分数区间  
				var yDataArr = Object.values(scoreGroups); // 纵坐标：对应人数  

				barChart.setOption({
					title: {
						text: '不同Co²回收段的人数变动折线图',
						left: 'center', // 标题居中显示  
						textStyle: { // 标题样式，可根据需要调整  
							color: '#000', // 标题颜色  
							fontSize: 18, // 标题字体大小 
							fontWeight: 'normal'
						}
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'cross',
							label: {
								backgroundColor: '#6a7985'
							}
						}
					},
					xAxis: {
						type: 'category',
						data: xDataArr, // 设置横坐标为分数区间  
						axisLabel: {
							formatter: function(value, index) {
								// 在每个标签后面添加 "Co²" 单位  
								return value + ' Co²';
							}
						}
					},
					yAxis: {
						type: 'value',
						name: '人数' // 纵坐标名称  
					},
					series: [{
						name: '人数',
						type: 'line', // 折线图类型  
						data: yDataArr, // 设置纵坐标为对应人数  
						smooth: true // 曲线平滑  
					}]
				});




			},


			updateCorrect() {
				var scoreGroups = {
					'0-30': 0,
					'31-60': 0,
					'61-90': 0, // 修正了区间标签  
					'91-100': 0 // 修正了区间标签  
				};

				// 遍历用户数据，计算每个区间的人数  
				this.users.forEach((user) => {
					var percentage = user.correctpercentage; // 确保使用了正确的变量  
					if (percentage <= 30) {
						scoreGroups['0-30']++;
					} else if (percentage <= 60) {
						scoreGroups['31-60']++;
					} else if (percentage <= 90) {
						scoreGroups['61-90']++;
					} else { // 不需要再检查是否小于等于100，因为已经覆盖了所有可能的情况  
						scoreGroups['91-100']++;
					}
				});

				// 计算总人数用于计算百分比  
				var totalCount = Object.values(scoreGroups).reduce((a, b) => a + b, 0);

				// 转换分数组为饼图所需的数据格式  
				var pieData = Object.entries(scoreGroups).map(([key, value]) => ({
					name: key,
					value: (value / totalCount * 100).toFixed(2) // 转换为百分比并保留两位小数  
				}));

				// 初始化饼图  
				var barChart = echarts.init(document.getElementById("my_bar_chart3"));
				barChart.setOption({
					title: {
						text: '答题正确率不同区段人数占比饼状图',
						subtext: '用户数据分析',
						left: 'center'
					},
					tooltip: {
						trigger: 'item',
						formatter: '{a} <br/>{b} : {c} ({d}%)'
					},
					series: [{
						name: '正确率区间(%) : 人数占比(%)',
						type: 'pie',
						radius: '55%',
						center: ['50%', '60%'],
						data: pieData,
						itemStyle: {
							emphasis: {
								shadowBlur: 10,
								shadowOffsetX: 0,
								shadowColor: 'rgba(0, 0, 0, 0.5)'
							}
						}
					}]
				});



			}




		}
	}
</script>

<style scoped>
	.TopNav {
		display: flex;
		justify-content: space-around;
		align-items: center;
		border: 1px solid #ebebeb;
		background-color: #f3f3f3;
		margin: 0 auto;
		width: 99vw;
	}

	.TopNav li {
		display: flex;
		flex-direction: column;
		position: relative;
		padding: 3vw;
		color: #333;
	}

	.TopNav li.select {
		border-bottom: 2px solid #fc9b39;
		font-weight: bold;
	}


	.swiper-container {
		min-height: 100vh;
		height: auto;
	}

	.card_row_line {
		display: flex;
		flex-direction: row;
		padding: 2vw;
		align-items: center;
	}

	.card_row_line+.card_row_line {
		border-top: 1px solid #ebebeb;
	}

	.card_row_line_img {
		width: 64px;
		height: 64px;
		border-radius: 10px;
	}

	.card_row_line_user {
		width: 85%;
		margin: 0vw 2vw 0vw 2vw;
		font-size: 36px;
	}

	.card_row_line_user_name {
		font-size: 38px;
		flex: 1;
	}

	.card_row_line_score {
		width: auto;
		white-space: nowrap;
		min-width: 12vw;
		background-color: #ff8002;
		text-align: center;
		border-radius: 10px;
		padding: 1vw;
		color: white;
	}


	.chart-container {
		width: 100%;
		display: flex;
		justify-content: center;
	}

	.chart {
		width: 90%;
		/* 设置图表宽度 */
		height: 80vw;
		/* 设置图表高度 */
	}

	.sum {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.sum div {
		font-size: 28px;
		color: #333;
		padding: 1vw;
	}

	.sum span {
		color: #ff8002;
		font-weight: bold;
		margin: 10px;
	}
</style>